<?php

namespace App\Http\Requests\Admin\CollPosition;
use App\Http\Requests\Request;
use App\Models\Common\CollPosition;
use Illuminate\Support\Facades\Validator;

class CreateRequest extends Request {
    public function authorize(){
        return true;
    }
    public function rules(){
        //添加职位类别排序判断
        Validator::extend('check_position_sort', function($attribute, $value, $parameters) {
            if($value!=0){
                if($this->grade == '2'){
                    $twoPosition = CollPosition::where('grade','2')->where('pid',$this->pid)->pluck('sort')->toArray();
                    if(in_array($value,$twoPosition)){
                        return false;
                    }else{
                        return true;
                    }
                }else if($this->grade == '3'){
                    $threePosition = CollPosition::where('grade','3')->where('pid',$this->pid)->pluck('sort')->toArray();
                    if(in_array($value,$threePosition)){
                        return false;
                    }else{
                        return true;
                    }
                }
            }else{
                return true;
            }
        });

        $input = $this->all();
        return [
            'name'=>'required',
            'cid'=>'required|numeric|max:999999|unique:coll_position,cid|cid_match:'.$input['grade'].','.$input['pid'],
            'sort'=>'check_position_sort'
        ];
    }
    public function messages(){
        $input = $this->all();
        $cid_match = '';
        if($input['grade'] == '2'){
            $two = substr($input['pid'],0,2);
            $end = '00';
            $cid_match = '职位类别编码必须以'.$two.'开头，'.$end.'结尾的6位数数字组合';
        }else if($input['grade'] == '3'){
            $three = substr($input['pid'],0,4);
            $cid_match = '职位类别编码必须以'.$three.'开头的6位数数字组合';
        }
        return [
            'name.required'=>'职位类别名称必须填写',
            'cid.required'=>'职位类别编码必须填写',
            'cid.unique'=>'职位类别编码已经存在',
            'cid.numeric'=>'职位类别编码必须是一个数字',
            'cid.max'=>'职位类别编码必须是一个6数字',
            'cid.cid_match'=>$cid_match,
            'sort.check_position_sort'=>'当前职位类别编码排序值已经存在'
        ];
    }
}
